<template>
  <div :class="`${prefixCls}`">
          <!--内容-->
    <div class="product-content">
      <div class="table-wrap">
        <a-tabs v-model:activeKey="stata.activeName" @change="handleClick">
          <a-tab-pane tab="全部订单" key="all"></a-tab-pane>
          <a-tab-pane :tab="'未付款(' + stata.order_count.payment + ')'" key="payment"></a-tab-pane>
          <a-tab-pane :tab="'待发货(' + stata.order_count.delivery + ')'" key="delivery"></a-tab-pane>
          <a-tab-pane :tab="'待收货(' + stata.order_count.received + ')'" key="received"></a-tab-pane>
          <a-tab-pane tab="已完成" key="six"></a-tab-pane>
          <a-tab-pane tab="已取消" key="cancel"></a-tab-pane>
          <a-tab-pane tab="取消申请中" key="cancelApply"></a-tab-pane>
        </a-tabs>

        <BasicTable @register="registerTable" v-loading="stata.loading">
          <template #action="{ record }">
            <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
          </template>
          
          <template #orderInfo="{ text, record, column }">
            <div class="order-code" v-if="record.isTopRow">
              <span class="state-text state-text-red" v-if="record.orderSource == '10'">{{ record.orderSourceText }}</span>
              <span class="state-text state-text-blue" v-if="record.orderSource == '11'">{{ record.orderSourceText }}</span>

              <span class="pl-4">订单号：{{ record.orderNo }}</span>
              <span class="pl16">下单时间：{{ record.createdAt }}</span>
              <span class="pl16" v-if="record.orderStatus == 21"><a-tag effect="dark" size="mini">取消申请中</a-tag></span>
            </div>
            <template v-else>
              <div class="product-info text-wrap" 
                :style="{width: column.width ? `${column.width}px` : '100%', height: '100%'}" 
                v-for="(item, index) in record.detailList" :key="index"
              >
                <div class="pic"><img alt="" :src="item.goodsImage" /></div>
                <div class="info">
                  <div class="name gray3 product-name">
                    <span>{{ item.goodsName }}</span>
                  </div>
                  <div class="gray9" v-if="item.goodsAttr">{{ item.goodsAttrValue }}</div>
                  <div class="orange" v-if="item.refundRealPrice > 0">{{ item.refundStatusName }}-{{ item.refundRealPrice }}</div>
                </div>
                <div class="d-c-c d-c">
                  <div class="orange">￥ {{ item.totalPayPrice }}</div>
                  <div class="gray3">x {{ item.number }}</div>
                </div>
              </div>
            </template>
          </template>

          <template #payAmount="{record}">
            <div v-if="!record.isTopRow">
              <div class="orange">{{ record.payPrice }}</div>
              <div v-if="record.deliveryPrice && record.deliveryPrice >0" class="gray9" style="margin-bottom: -2px;">(含运费：{{ record.deliveryPrice }})</div>
              <div v-if="record.totalBagPrice && record.totalBagPrice >0" class="gray9">(含包装费：{{ record.totalBagPrice }})</div>
              <div v-if="record.refundPrice && record.refundPrice >0" class="red">(已退款：{{ record.refundPrice }})</div>
            </div>
          </template>

          <template  #orderStatus="{ record }" >
            <div v-if="!record.isTopRow">
              {{ record.orderStatusText }}
            </div>
          </template>

          <template #payWay="{ record }" >
            <div v-if="!record.isTopRow">
              {{ record.payWayName }}
            </div>
          </template>

          <template  #storeName="{ record }" >
            <div v-if="!record.isTopRow">
              {{ record.tenantName }}
            </div>
          </template>

          <template #buyer="{ record, column }" >
            <div v-if="!record.isTopRow" :style="{width: column.width ? `${column.width}px` : '100%', height: '100%'}">
              <div>{{ record.nickName }}</div>
              <div class="gray9">ID：({{ record.userId }})</div>
              <div class="gray9" v-if="record.buyerRemark">备注：({{ record.buyerRemark }})</div>
            </div>
          </template>

          <template #deliveryWay="{ record, column }">
            <div v-if="!record.isTopRow" :style="{width: column.width ? `${column.width}px` : '100%', height: '100%'}">
              <div class="green">{{ record.deliveryWayText}}</div>
              <span class="red text-wrap" v-if="record.deliveryNoStr">取餐码: {{ record.deliveryNoStr}}</span>
            </div>
          </template>

          <template #evaluate="{ record }" >
            <div v-if="!record.isTopRow">
              <span v-if="!record.isEvaluate">未评价</span>
              <span v-else="">已评价</span>
            </div>
          </template>
        </BasicTable>
        <div style="display: flex; width: 100%;">
          <Pagination
            style="margin-left: auto"
            v-model:current="stata.paginationInfo.current"
            size="small"
            v-bind="stata.paginationInfo"
            @change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <Refund @register="registerRefund" @success="reload" />
  </div>
</template>
<script lang="ts" name="order-shop" setup>
  import { ref, onUnmounted, onMounted, reactive } from "vue"
  import { BasicTable, BasicColumn, TableAction, ActionItem} from "/@/components/Table"
  import { useDesign } from "/@/hooks/web/useDesign"
  import { useI18n } from "/@/hooks/web/useI18n"
  import * as orderApi from './api'
  import { Table, Pagination } from 'ant-design-vue';
  import { PAGE_SIZE, PAGE_SIZE_OPTIONS, FETCH_SETTING } from "/@/components/Table/src/const"
  import { randomString } from "/@/utils/common/compUtils"
  import { useModal } from "/@/components/Modal"
  import { useListPage } from "/@/hooks/system/useListPage"
  import { columns, sharedOnCell } from './data'
  import { PayStatus } from '../data'
  import Refund from '../RefundModal.vue'
  const [registerRefund, { openModal: openRefund }] = useModal()
  const { t } = useI18n()
  const { prefixCls } = useDesign("order")
  const { tableContext } = useListPage({
    designScope: "order",
    tableProps: {
      pagination: false,
      // api: list,
      dataSource: [],
      bordered: true,
      canResize: false,
      columns: columns,
      size: "small",
      useSearchForm: false,
      showTableSetting: false,
      formConfig: {
        // schemas: searchFormSchema,
      },
      scroll: {
        x: 'max-content',
      },
      actionColumn: {
        title: "操作",
        dataIndex: "action",
        align: "center",
        // minWidth: 160,
        fixed: 'right',
        customCell: sharedOnCell,
        slots: { customRender: "action" },
      },
      beforeFetch: (params) => {
        return Object.assign({ column: "createTime", order: "desc" }, params)
      },
    }
  })
  const [registerTable, { reload, setTableData }, { }] = tableContext

  const stata = reactive<any>({
    /*切换菜单*/
    activeName: 'all',
    /*是否加载完成*/
    loading: true,
    /*列表数据*/
    dataSource: [],
    formQueryParams: {
   
    },
    paginationInfo: {
      total: 0,
      current: 1,
      showQuickJumper: true,
      showTotal: (total) => t("component.table.total", { total }),
      showSizeChanger: true,
      defaultPageSize: PAGE_SIZE,
      pageSizeOptions: PAGE_SIZE_OPTIONS,
    },
    tempDataSource: [
      
    ],
    /*一页多少条*/
    pageSize: 10,
    /*一共多少条数据*/
    totalDataNumber: 0,
    /*当前是第几页*/
    curPage: 1,
    /*横向表单数据模型*/
    searchForm: {
      orderNo: '',
      style_id: '',
      store_id: '',
      createTime: ''
    },
    /*配送方式*/
    exStyle: [],
    /*门店列表*/
    shopList: [],
    /*时间*/
    create_time: '',
    /*统计*/
    order_count: {
      payment: 0,
      delivery: 0,
      received: 0
    },
    dialogBatchDelivery: false,
    /*是否打开编辑弹窗*/
    open_edit: false,
    /*当前编辑的对象*/
    order_no: ''
  })


  onMounted(() => {
    handlePageChange(1)
  })

  /* 切换菜单 */
  const handleClick = (tab, event) => {

  }

  const handlePageChange = async (page, pageSize = PAGE_SIZE) => {
    stata.loading = true
    try {
      console.log("onPageChange", page, pageSize)
      const requestParams = { ...stata.formQueryParams }
      requestParams[FETCH_SETTING.pageField] = page
      requestParams[FETCH_SETTING.sizeField] = pageSize
      const result = await orderApi.pageOrder(requestParams)
      const dataSource = result.records || []

      stata.paginationInfo.total = result.total || 0
      stata.dataSource = []
      dataSource.forEach(data => {
        data.deliveryNoStr = data.deliveryNos?.join('，')
        data.detailList.forEach(item => {
          item.goodsAttrValue = item.goodsAttr?.map(e => {
            return e.values.map(v => {
              return v.name + (v.addPrice > 0 ? `￥(${v.addPrice})` : '')
            }).join('；')
          }).join('；')
        })
        stata.dataSource.push({
          ...data,
          isTopRow: true
        })
        stata.dataSource.push({
          ...data,
          isTopRow: false
        })
      })

      setTableData(stata.dataSource)
    } finally {
      stata.loading = false
    }
  }


  const getTableAction = (record): ActionItem[] => {
    return [
      {
        label: "删除",
        color: 'error',
        popConfirm: {
          title: "是否确认删除",
          confirm: handleClick.bind(null, record),
        },
      },
      {
        label: "退款",
        ifShow: record.refundStatus != PayStatus.REFUND_ALL && record.payStatus == PayStatus.PAY_SUCCESS,
        onClick: handleOpenRefund.bind(null, record),
      },
      
      {
        label: "详情",
        // onClick: handleDetail.bind(null, record),
      },
    ]
  }

  const getDropDownAction = (record): ActionItem[] => {
    return [
      
    ]
  }

  const handleOpenRefund = (record) => {
    openRefund(true, { record: { ...record }, refundApi: orderApi.refund })
  }
</script>

<style lang="less">
@prefix-cls: ~"@{namespace}-order";

@import url('../style.less');

.@{prefix-cls}  {
  .product-info {
    padding: 10px 0;
    border-top: 1px solid #eeeeee;
  }

  // .order-code .state-text {
  //   padding: 2px 4px;
  //   border-radius: 4px;
  //   background-color: #808080;
  //   color: #ffffff;
  // }

  // .order-code .state-text-red {
  //   background: red !important;
  // }

  // .table-wrap .product-info:first-of-type {
  //   border-top: none;
  // }

  // .table-wrap .a-table-body tbody .a-table-row:nth-child(odd) {
  //   background: #f5f7fa;
  // }
}

</style>
